package com.app.business.service;

import com.app.business.en.Status;
import com.app.business.model.OverAreaPrice;
import com.app.business.model.ZsProject;
import com.app.business.utils.UserPermissionUtil;
import com.app.system.jpa.JpaBaseDao;
import com.app.system.jpa.PageBean;
import com.app.system.jpa.Wrapper;
import com.app.system.permission.model.UserInfo;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.WebUtils;
import com.app.system.utils.dataType.BigDecimalUtils;
import com.app.system.utils.dataType.StringUtils;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.*;

/**
 * 征收项目管理
 * Created by yby on 2019/2/11 14:45.
 */
@Service
@Transactional
public class ZsProjectService extends JpaBaseDao<ZsProject, Integer> {

    @Autowired
    private OverAreaPriceService overAreaPriceService;
    @Autowired
    private HouseService houseService;

    /**
     * 分页处理
     *
     * @return
     */
    public PageBean<ZsProject> getZsProjectPageBean() {
        //查询语句
        StringBuffer query = new StringBuffer(" zsp from ZsProject zsp ");

        //默认排序(PageBean指定排序字段类型的话，则默认排序不使用)
        StringBuffer orderBy = new StringBuffer("zsp.town,zsp.startYear desc,zsp.projectName");
        Wrapper wrapper = new Wrapper(query, orderBy);
        wrapper.initSearchParams();


        //用户只能看到已经分配给自己的项目下协议信息
        UserPermissionUtil.zsProjectUserLimit(wrapper);

        return this.pageHql(wrapper);
    }

    /**
     * 得到征收项目列表（根据当前用户）
     *
     * @return
     */
    public List<ZsProject> zsProjectList() {
        //查询语句
        StringBuffer hql = new StringBuffer("from ZsProject zs where zs.id in (:zsProjectId) order by zs.town,zs.startYear desc,zs.id");
        Map<String, Object> map = new HashMap<>();
        map.put("zsProjectId", UserPermissionUtil.getZsProjectIdListByUser());
        return this.findHql(hql.toString(), map);
    }


    /**
     * 得到征收项目列表（根据当前选房年份、片区、安置区）
     *
     * @return
     */
    public List<ZsProject> getZsProjectListByTownCodeAndYearAndAzpId(String townCode, String yearStr, Integer azProjectId) {
        //查询语句
        StringBuffer hql = new StringBuffer("from ZsProject zsp where 1=1 ");
        Map<String, Object> map = new HashMap<>();

        List<Integer> zspIdList = new ArrayList<>();
        zspIdList.add(0);//防止为空
        zspIdList = this.houseService.getZspIdListByChooseHouseDateYear(townCode, yearStr, azProjectId);
        hql.append(" and zsp.id in :zspIdList");
        map.put("zspIdList", zspIdList);

        hql.append(" order by zsp.town,zsp.startYear desc,zsp.id");
        return this.findHql(hql.toString(), map);
    }

    /**
     * 得到征收项目列表
     *
     * @return
     */
    public List<ZsProject> zsProjectAllList() {
        //查询语句
        StringBuffer hql = new StringBuffer("from ZsProject zs  order by zs.town,zs.startYear desc,zs.id");
        return this.findHql(hql.toString(), null);
    }

    /**
     * 如果是新建的项目，默认直接保存下列的参数配置
     *
     * @param zsProjectId
     */
    public synchronized void saveParamData(Integer zsProjectId) {
        ZsProject zsProject = this.findOne(zsProjectId);
        Precondition.checkSqdsArguement(zsProject != null, "未找到征收项目！");
        zsProject.setXfbcPrice(new BigDecimal("3000"));   //选房不足补偿单价
        zsProject.setCwjPrice(new BigDecimal("2000"));   //储物间申购单价
        zsProject.setZzwxPrice(new BigDecimal("90"));   //住宅维修基金标准单价
        zsProject.setZzbcwxPrice(new BigDecimal("10"));   //住宅维修基金本次单价
        zsProject.setCcjwxPrice(new BigDecimal("90"));   //储藏间维修基金标准单价
        zsProject.setCcjbcwxPrice(new BigDecimal("10"));   //储藏间维修基金本次单价
        zsProject.setCwwxPrice(new BigDecimal("50"));   //车位维修基金标准单价
        zsProject.setCwbcwxPrice(new BigDecimal("50"));   //车位维修基金本次单价
        zsProject.setGdbzPrice(new BigDecimal("6"));   //过渡补助费单价
        //保存之前先删除数据
        this.overAreaPriceService.deleteOverAreaPriceByZsProjectId(zsProject.getId());
        for (int i = 0; i <= 3; i++) {
            OverAreaPrice overAreaPrce = new OverAreaPrice();
            if (i == 0) {
                overAreaPrce.setMinArea(new BigDecimal("0"));
                overAreaPrce.setMaxArea(new BigDecimal("10"));
                overAreaPrce.setPrice(new BigDecimal("1500"));
            } else if (i == 1) {
                overAreaPrce.setMinArea(new BigDecimal("10"));
                overAreaPrce.setMaxArea(new BigDecimal("20"));
                overAreaPrce.setPrice(new BigDecimal("2600"));
            } else if (i == 2) {
                overAreaPrce.setMinArea(new BigDecimal("20"));
                overAreaPrce.setMaxArea(new BigDecimal("40"));
                overAreaPrce.setPrice(new BigDecimal("3000"));
            } else {
                overAreaPrce.setMinArea(new BigDecimal("40"));
                overAreaPrce.setMaxArea(new BigDecimal("9999"));
                overAreaPrce.setPrice(new BigDecimal("5600"));
            }
            overAreaPrce.setSortNum(i + 10);
            overAreaPrce.setZsProject(zsProject);
            this.overAreaPriceService.save(overAreaPrce);
        }
    }

    /**
     * 征收项目参数配置数据保存
     *
     * @param request
     * @return
     */
    public synchronized Response dataFormSave(HttpServletRequest request) {
        int zsProjectId = ParamUtils.getInt(request, "zsProjectId", 0);
        ZsProject zsProject = this.findOne(zsProjectId);
        Precondition.checkAjaxArguement(zsProject != null, "1111", "未找到征收项目，保存失败！");
        WebUtils.bind(request, zsProject);
        this.save(zsProject);
        //保存之前先删除数据
        this.overAreaPriceService.deleteOverAreaPriceByZsProjectId(zsProject.getId());

        String[] minAreaArray = ParamUtils.getStringParameters(request, "minArea");    //最小面积
        String[] maxAreaArray = ParamUtils.getStringParameters(request, "maxArea");    //最大面积
        String[] priceArray = ParamUtils.getStringParameters(request, "price");    //购房单价
        String[] sortNumArray = ParamUtils.getStringParameters(request, "sortNum");    //排序号
        //必须不为空，且长度一致（必填）
        Precondition.checkAjaxArguement(minAreaArray != null && maxAreaArray != null && minAreaArray.length == maxAreaArray.length, "2222", "面积区间数据填写不规范！");
        int length = minAreaArray.length;
        String minArea = null, maxArea = null, price = null, sortNum = null;
        for (int i = 0; i < length; i++) {
            minArea = null;
            maxArea = null;
            price = null;
            sortNum = null;
            minArea = minAreaArray[i];
            maxArea = maxAreaArray[i];
            price = priceArray[i];
            sortNum = sortNumArray[i];
            if (minArea != null && !minArea.equals("") && maxArea != null && !maxArea.equals("") && price != null && !price.equals("") && sortNum != null && !sortNum.equals("")) {
                OverAreaPrice overAreaPrice = new OverAreaPrice();
                overAreaPrice.setMinArea(BigDecimalUtils. stringToBigDecimal(minArea));   //最小面积
                overAreaPrice.setMaxArea(BigDecimalUtils.stringToBigDecimal(maxArea));   //最大面积
                overAreaPrice.setPrice(BigDecimalUtils.stringToBigDecimal(price));   //补偿单价
                overAreaPrice.setSortNum(Integer.valueOf(sortNum));    //排序号
                overAreaPrice.setZsProject(zsProject);   //征收项目
                this.overAreaPriceService.save(overAreaPrice);
            }
        }
        return new Response("0001", "保存成功!");
    }

    /**
     * 得到征收项目map
     * key:town   value:list
     *
     * @return
     */
    public Map<String, List<ZsProject>> getZsProjectMap() {
        StringBuffer hql = new StringBuffer("from ZsProject zs where zs.hideStatus =:hideStatus order by zs.town,zs.startYear desc,zs.id");
        Map<String, Object> map = new HashMap<>();
        map.put("hideStatus", Status.NO.getIndex());
        List<ZsProject> zsProjectList = this.findHql(hql.toString(), map);
        Map<String, List<ZsProject>> resultMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(zsProjectList)) {
            List<ZsProject> itemList = Lists.newLinkedList();
            for (ZsProject zsProject : zsProjectList) {
                itemList = null;
                itemList = resultMap.get(zsProject.getTown()) == null ? Lists.newLinkedList() : resultMap.get(zsProject.getTown());
                itemList.add(zsProject);
                resultMap.put(zsProject.getTown(), itemList);
            }
        }
        return resultMap;
    }

    /**
     * 获取某些征收项目
     *
     * @param zsProjectIdStr
     * @return
     */
    public List<ZsProject> getZsProjectListByZsProjectIdStr(String zsProjectIdStr) {
        StringBuffer hql = new StringBuffer("from ZsProject zs where zs.id in (" + zsProjectIdStr + ") order by zs.startYear desc,zs.id");
        return this.findHql(hql.toString(), null);
    }
}
